import { io, Socket } from "socket.io-client";
import { v4 as uuidv4 } from "uuid";
import chalk from "chalk-web";
export class Connector {
  client: Socket | null = null;
  connectCallBack: Function | null = null;
  disconnectCallBack: Function | null = null;
  version = "0.0.3"

  constructor() {}

  connect(
    name = "baize_client",
    url = "http://localhost:3000",
    options: any = {}
  ) {
    const socket = io(url, {
      timeout: options.timeout || 2000,
      path: options.path ?? "/socket.io",
    });
    this.client = socket;
    socket.connect();

    socket.on("connect", () => {
      chalk("green", "🛜信号", name + "连接成功");
      socket.emit("join", name);
      if (this.connectCallBack) this.connectCallBack();
    });

    socket.on("disconnect", () => {
      chalk("green", "🛜信号", name + "断开连接");
      if (this.disconnectCallBack) this.disconnectCallBack();
    });
  }

  register(funcName: string, func: any) {
    (this as any)[funcName] = func.bind(this);
    return this;
  }

  disconnect() {
    if (this.client == null) return Promise.reject("未初始化,请先调用connect");
    this.client?.emit("close", 1);
  }

  request(Topic: string, Type: string, Params: any) {
    if (this.client == null) return Promise.reject("连接未初始化");
    const Tag = uuidv4();
    const req = {
      Topic,
      Type,
      Params,
      Req: 1,
      Res: 0,
      Tag,
    };
    if (Topic === "api") {
      this.client?.emit("api", req);
    }
    if (Topic === "command") {
      this.client?.emit("command", req);
    }
    chalk("orange","🛜发出", req);
    return new Promise((resolve) => {
      this.client?.once(req.Tag, (ev: any) => {
        chalk("green", "🛜返回", ev);
        resolve(ev);
      });
    });
  }
}
